/*
 *Copyright (c) 2024 Black Sesame Technologies
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
*/

#include "hscg_firmware_statistic.h"
#include "eth2can.h"

#ifdef STATISTICS_CODE_TIMESTAMP_ENABLE

#ifndef MAX
#define MAX(a, b) ((a) > (b)? (a) : (b))
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b)? (a) : (b))
#endif

/* max size: 256k 0x40000 */
struct statistics_code_timestamp_t *statistics_code_timestamp =
    (struct statistics_code_timestamp_t *)STATISTICS_CODE_TIMESTAMP_SRAM_ADDR;

void statistics_code_loop_inc(void)
{

    statistics->runtime_total++;
    if (statistics->code_timestamp_loop >= (STATISTICS_CODE_TIMESTAMP_GRPNUM -1))
        statistics->code_timestamp_loop = 0;
    else
        statistics->code_timestamp_loop++;
}

void statistics_code_timestamps_update(uint32 step_inx)
{
    uint64 delay;
    uint32 step;
    uint32 loop = statistics->code_timestamp_loop;

    if (step_inx >= TIMESTAMP_CODE_NUM)
        statistics->code_timestamp_step = 0;
    else
        statistics->code_timestamp_step = step_inx;

    step = statistics->code_timestamp_step;
    statistics_code_timestamp[loop].timestamp[step] = util_get_GTC_time64();
    if (step) {
        delay = statistics_code_timestamp[loop].timestamp[step] - statistics_code_timestamp[loop].timestamp[step - 1];
        if (!statistics_code_timestamp[loop].min_delay[step])
            statistics_code_timestamp[loop].min_delay[step] = delay;
        if (delay > 0)
            statistics_code_timestamp[loop].min_delay[step] =
                MIN(delay, statistics_code_timestamp[loop].min_delay[step]);
        statistics_code_timestamp[loop].max_delay[step] = MAX(delay, statistics_code_timestamp[loop].max_delay[step]);
    }
}

void statistics_code_timestamp_init(void)
{
    int i;

    if (sizeof(struct statistics_code_timestamp_t) > (STATISTICS_CODE_TIMESTAMP_SRAM_ADDR_END - STATISTICS_CODE_TIMESTAMP_SRAM_ADDR)) {
        hprintf(DEBUG, "Error: %s: size of struct statistics_code_timestamp_t is too large!\n", __func__);
        return;
    }

    for (i = 0; i < STATISTICS_CODE_TIMESTAMP_GRPNUM; i++) {
        memset(&statistics_code_timestamp[i], 0, sizeof(struct statistics_code_timestamp_t));
    }
}

#endif /* STATISTICS_CODE_TIMESTAMP_ENABLE */